<script setup>
import GoBackAndSearchNav from "@/components/GoBackAndSearchNav.vue";
import {preview} from 'vue3-image-preview';
import {Plus} from '@element-plus/icons-vue'
import {onMounted, ref, reactive} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import useOrderStore from "@/store/modules/OrderStore.js";
import {showImagePreview} from 'vant';
import 'vant/es/image-preview/style'
import 'vant/es/dialog/style'
import {addPercentageInterval, INTERVAL_FIELD_NAME} from "@/utils/FileUtils.js";
import {FILE_URL_FIELD_NAME, fileUploadAPI, TIP_MSG_FIELD_NAME} from "@/api/file.js";
import {elErrorMessageTip, elSuccessMessageTip} from "@/utils/MessageTipUtils.js";
import {commentAPI, getAllOrderAPI} from "@/api/order.js";
import {ORDER_LIST_ROUTE} from "@/router/routes/order/OrderList.js";

const route = useRoute()
const router = useRouter()

const order = ref({})
const getOrder = () => {
  const orderStore = useOrderStore()
  const allOrder = orderStore.all
  const orderId = Number.parseInt(route.query.orderId)
  for (let o of allOrder) {
    if (o.id === orderId) {
      order.value = o
      break
    }
  }
}
onMounted(async () => {
  getOrder()
})

// 图片预览
const imgPreview = () => {
  showImagePreview([order.value.productOptionImg]);
}

const rate = ref(5)
const comment = ref('')

// ***********
// * 商品图片 *
// ***********
const productImgList = ref([])
// 商品图片索引
let productImgIdx = 0
const imgUpload = async (file, fileList) => {
  file = reactive(file)
  fileList.value.push(file)
  file.status = 'uploading'
  file['idx'] = productImgIdx++
  // 文件上传进度计时器
  addPercentageInterval(file)
  // 文件上传
  const res = await fileUploadAPI(file.raw)
  if (res.status) {
    // 成功
    // 清除计时器
    clearInterval(file[INTERVAL_FIELD_NAME])
    elSuccessMessageTip(res[TIP_MSG_FIELD_NAME])
    file.status = 'success'
    file.percentage = 100
    file.url = res[FILE_URL_FIELD_NAME]
  } else {
    // 失败
    // 清除计时器
    clearInterval(file[INTERVAL_FIELD_NAME])
    elErrorMessageTip(res[TIP_MSG_FIELD_NAME])
    file.status = 'fail'
  }
}
// 商品图片上传
const productImgUpload = (file) => {
  imgUpload(file, productImgList)
}
// 图片预览
const productImgPreview = (img) => {
  const previewImgIdx = img.idx
  preview({images: productImgList.value, index: productImgIdx})
}

const commentHandler = async () => {
  if (comment.value.length <= 0) {
    elErrorMessageTip("评论内容不能为空")
    return
  }
  const res = await commentAPI(
      order.value.id, order.value.productId, order.value.userId,
      comment.value, rate.value,
      productImgList.value.map(i => i.url)
  )
  if (res) {
    // router.back()
    useOrderStore().saveAll(await getAllOrderAPI())
    router.replace({name: ORDER_LIST_ROUTE, query: {tabActive: 5}})
  }
}
</script>

<template>
  <div class="comment">
    <GoBackAndSearchNav :title="'商品评论'" :placeholder="true"></GoBackAndSearchNav>
    <van-cell-group inset title="商品信息">
      <van-cell class="flex-center" title="商品图片">
        <template #value>
          <div class="flex justify-end items-center">
            <div class="w-12 h-12" @click="imgPreview">
              <img :src="order?.productOptionImg" alt="">
            </div>
          </div>
        </template>
      </van-cell>
      <van-cell title="商品名称" :label="order.title" />
      <van-cell title="商品选项" :label="order.productOptionName" />
    </van-cell-group>
    <van-cell-group inset title="评分">
      <van-cell class="flex-center" title="商品评分">
        <template #value>
          <div class="flex justify-end items-center">
            <van-rate v-model="rate" />
          </div>
        </template>
      </van-cell>
    </van-cell-group>
    <van-cell-group inset title="评价">
      <div>
        <van-field
            v-model="comment"
            rows="1"
            autosize
            label=""
            maxlength="255"
            show-word-limit
            clearable
            type="textarea"
            placeholder="请输入商品评价"
        />
      </div>
    </van-cell-group>
    <van-cell-group inset title="图片上传">
      <div class="p-2">
        <el-upload
            class="uploader"
            v-model:file-list="productImgList"
            list-type="picture-card"
            :auto-upload="false"
            multiple
            :on-change="productImgUpload"
            :on-preview="productImgPreview"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
      </div>
    </van-cell-group>
    <div class="m-4">
      <van-button @click="commentHandler" round type="primary" block>提交评价</van-button>
    </div>
  </div>
</template>

<style scoped lang="scss">

</style>